<template>
  <base-layout>
    <div class="page-container">
      <div class="space-y-6">
        <!-- Status Header Section -->
        <a-card class="shadow-sm" :loading="loading">
          <div class="flex items-center justify-between">
            <div class="space-y-2">
              <h1 class="text-2xl font-semibold text-gray-800">代码评估结果</h1>
              <div class="flex items-center space-x-2">
                <a-tag :color="getStatusColor(submission?.status)">
                  {{ getStatusText(submission?.status) }}
                </a-tag>
                <span class="text-gray-500">•</span>
                <span class="text-gray-600">执行时间: {{ submission?.time }}ms</span>
                <span class="text-gray-500">•</span>
                <span class="text-gray-600">内存使用: {{ formatMemory(submission?.memory) }}</span>
              </div>
            </div>
            <div class="flex items-center space-x-4">
              <a-button @click="copyCode" :disabled="!submission?.code">
                <template #icon><CopyOutlined /></template>
                复制代码
              </a-button>
              <a-button type="primary" @click="backToEdit">
                <template #icon><EditOutlined /></template>
                重新编写
              </a-button>
              <a-button @click="backToList">
                <template #icon><UnorderedListOutlined /></template>
                返回题目列表
              </a-button>
            </div>
          </div>
        </a-card>

        <!-- Test Cases Section -->
        <a-card class="shadow-sm" :loading="loading">
          <template #title>
            <span class="text-lg font-medium text-gray-800">测试用例结果</span>
          </template>
          <div class="test-cases-grid">
            <a-card 
              v-for="testCase in judgeCaseList" 
              :key="testCase.seq"
              :class="getTestCaseCardClass(testCase.status)"
              size="small"
            >
              <div class="flex items-center justify-between mb-2">
                <span class="font-medium" :class="getTestCaseTextClass(testCase.status)">
                  用例 #{{ testCase.seq }}
                </span>
                <CheckCircleFilled v-if="testCase.status === 0" class="text-success" />
                <CloseCircleFilled v-else class="text-error" />
              </div>
              <div class="text-sm" :class="getTestCaseTextClass(testCase.status)">
                <div>执行时间: {{ testCase.time }}ms</div>
                <div>内存使用: {{ formatMemory(testCase.memory) }}</div>
              </div>
            </a-card>
          </div>
        </a-card>

        <!-- Code Section -->
        <a-card class="shadow-sm" :loading="loading">
          <template #title>
            <div class="flex items-center justify-between">
              <div class="flex items-center space-x-3">
                <div class="flex items-center h-6">
                  <span class="text-gray-700 font-medium leading-6">Solution.{{ getFileExtension(submission?.language) }}</span>
                  <a-tag class="ml-[10px] h-6 leading-6 flex items-center">{{ submission?.language }}</a-tag>
                </div>
              </div>
              <div class="flex items-center space-x-2">
                <a-button type="text" @click="copyCode" :disabled="!submission?.code">
                  <template #icon><CopyOutlined /></template>
                </a-button>
                <a-button type="text" @click="toggleFullscreen">
                  <template #icon><ExpandOutlined /></template>
                </a-button>
              </div>
            </div>
          </template>
          <div class="code-section bg-gray-50 p-4 rounded-lg">
            <pre class="text-sm overflow-x-auto"><code ref="codeBlock" :class="'language-' + submission?.language?.toLowerCase()">{{ submission?.code }}</code></pre>
          </div>
        </a-card>
      </div>
    </div>
  </base-layout>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useJudgeResult } from '@/composables/useJudgeResult';
import BaseLayout from '@/components/layout/BaseLayout.vue';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
import {
  CopyOutlined,
  EditOutlined,
  ExpandOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  UnorderedListOutlined
} from '@ant-design/icons-vue';

const route = useRoute();
const router = useRouter();
const { submission, judgeCaseList, loading, fetchJudgeResult, handleReJudge } = useJudgeResult();
const isFullscreen = ref(false);
const codeBlock = ref(null);

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 0:
      return 'success';
    case -1:
    case -2:
    case -3:
    case -4:
    case -5:
    case -999:
      return 'error';
    default:
      return 'default';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '通过';
    case -1:
      return '答案错误';
    case -2:
      return '编译错误';
    case -3:
      return '运行时错误';
    case -4:
      return '超时';
    case -5:
      return '内存超限';
    case -999:
      return '失败';
    default:
      return '未知';
  }
};

// 格式化内存使用
const formatMemory = (memory) => {
  return (memory / 1024).toFixed(1) + 'MB';
};

// 获取文件扩展名
const getFileExtension = (language) => {
  const extensions = {
    'Java': 'java',
    'Python': 'py',
    'C++': 'cpp',
    'C': 'c'
  };
  return extensions[language] || 'txt';
};

// 获取测试用例卡片样式
const getTestCaseCardClass = (status) => {
  return status === 0 
    ? 'bg-success-50 border-success-200 hover:bg-success-100' 
    : 'bg-error-50 border-error-200 hover:bg-error-100';
};

// 获取测试用例文本样式
const getTestCaseTextClass = (status) => {
  return status === 0 ? 'text-success-700' : 'text-error-700';
};

// 复制代码
const copyCode = () => {
  if (!submission.value?.code) return;
  
  navigator.clipboard.writeText(submission.value.code)
    .then(() => message.success('代码已复制到剪贴板'))
    .catch(() => message.error('复制失败'));
};

// 返回到题目编辑页面
const backToEdit = () => {
  if (submission.value?.displayPid) {
    router.push(`/oj/problem/${submission.value.displayPid}`);
  } else {
    message.error('无法获取题目信息');
  }
};

// 返回题目列表
const backToList = () => {
  router.push('/oj');
};

// 切换全屏
const toggleFullscreen = () => {
  const codeSection = document.querySelector('.code-section');
  if (!codeSection) return;

  if (!isFullscreen.value) {
    if (codeSection.requestFullscreen) {
      codeSection.requestFullscreen();
    } else if (codeSection.webkitRequestFullscreen) {
      codeSection.webkitRequestFullscreen();
    } else if (codeSection.msRequestFullscreen) {
      codeSection.msRequestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
  isFullscreen.value = !isFullscreen.value;
};

// 监听全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!(
    document.fullscreenElement ||
    document.webkitFullscreenElement ||
    document.msFullscreenElement
  );
};

onMounted(() => {
  // 获取评测结果
  fetchJudgeResult(route.params.id);
  
  // 添加全屏变化监听
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.addEventListener('msfullscreenchange', handleFullscreenChange);
  
  // 初始化代码高亮
  nextTick(() => {
    if (codeBlock.value) {
      hljs.highlightElement(codeBlock.value);
    }
  });
});

// 监听代码变化，重新应用高亮
watch(() => submission.value?.code, () => {
  nextTick(() => {
    if (codeBlock.value) {
      hljs.highlightElement(codeBlock.value);
    }
  });
});

onUnmounted(() => {
  // 移除全屏变化监听
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.removeEventListener('msfullscreenchange', handleFullscreenChange);
});
</script>

<style scoped>
.page-container {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.space-y-6 > * + * {
  margin-top: 1.5rem;
}

.test-cases-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 16px;
  padding: 0 8px;
}

@media (max-width: 1280px) {
  .test-cases-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 1024px) {
  .test-cases-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .test-cases-grid {
    grid-template-columns: repeat(2, 1fr);
    padding: 0 4px;
  }
}

.bg-success-50 {
  background-color: #f6ffed;
}

.border-success-200 {
  border-color: #b7eb8f;
}

.text-success-700 {
  color: #389e0d;
}

.bg-error-50 {
  background-color: #fff2f0;
}

.border-error-200 {
  border-color: #ffccc7;
}

.text-error-700 {
  color: #cf1322;
}

/* 全屏模式样式 */
.code-section:fullscreen {
  padding: 2rem;
  background-color: white;
}

.code-section:fullscreen pre {
  font-size: 1.1rem;
  line-height: 1.6;
}

/* 代码高亮样式 */
:deep(.hljs) {
  background: #f6f8fa;
  border-radius: 6px;
  padding: 1rem;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
}

:deep(.hljs-keyword) {
  color: #d73a49;
  font-weight: 600;
}

:deep(.hljs-string) {
  color: #032f62;
}

:deep(.hljs-number) {
  color: #005cc5;
}

:deep(.hljs-comment) {
  color: #6a737d;
  font-style: italic;
}

:deep(.hljs-function) {
  color: #6f42c1;
}

:deep(.hljs-class) {
  color: #22863a;
}

:deep(.hljs-variable) {
  color: #24292e;
}

:deep(.hljs-operator) {
  color: #d73a49;
}

:deep(.hljs-punctuation) {
  color: #24292e;
}

:deep(.hljs-property) {
  color: #005cc5;
}

:deep(.hljs-attr) {
  color: #005cc5;
}

:deep(.ant-tag) {
  margin: 0;
  line-height: 1;
  height: 24px;
  padding: 0 8px;
  display: inline-flex;
  align-items: center;
}
</style> 